package com.newgoldcurrency.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.webkit.JavascriptInterface;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.databinding.DialogVerifyBinding;

public class VerifyDialog extends Dialog {
    private final DialogVerifyBinding binding;
    private final Activity activity;
    private final Verify verify;
    @SuppressLint("SetJavaScriptEnabled")
    public VerifyDialog(Activity activity,Verify verify) {
        super(activity);
        this.activity=activity;
        this.verify=verify;
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        binding = DialogVerifyBinding.inflate(activity.getLayoutInflater());
        binding.dialogVerifyWeb.clearCache(true);
        binding.dialogVerifyWeb.getSettings().setJavaScriptEnabled(true);
        binding.dialogVerifyWeb.setWebViewClient(new WebViewClient());
        binding.dialogVerifyWeb.addJavascriptInterface(new VerifyListener(), "VerifyListener");
        binding.dialogVerifyWeb.loadUrl("http://goldht.goldrr.com/validate.html");
        setContentView(binding.getRoot());
    }
    public  interface Verify{
        void success();
    }
    private class VerifyListener  {
        @JavascriptInterface
        public void callback(String result) {
            try {
                activity.runOnUiThread(() -> {
                    JsonObject jo = JsonParser.parseString(result).getAsJsonObject();
                    if (jo.get("data").getAsJsonObject().get("isValid").getAsBoolean()){
                        verify.success();
                    }else {
                        Toast.makeText(activity, "CAPTCHA failed", Toast.LENGTH_SHORT).show();
                    }
                    dismiss();
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}